//
//  COBindEmailController.swift
//  CocoProject
//
//  Created by Vill on 2023/11/16.
//

import UIKit

class COBindEmailController: COBaseController {
    
    var type = 0
    
    lazy var containView: UIView = {
        let con = UIView()
        con.backgroundColor = .white
        return con
    }()
    
    lazy var emailContainer: UIView = {
        let emailcontain = UIView()
        emailcontain.backgroundColor = UIColor.colorWithHex("#F5F5F5")
        emailcontain.layer.cornerRadius = PTW(65/2)
        emailcontain.layer.masksToBounds = true
        return emailcontain
    }()

    lazy var emailImg: UIImageView = {
        let emImg = UIImageView()
        emImg.image = KImaged("coco_mine_email")
        return emImg
    }()

    lazy var emailTxtField: UITextField = {
        let txt = UITextField()
        txt.backgroundColor = .clear
        txt.clearButtonMode = .whileEditing
        let attributes = [NSAttributedString.Key.font:UIFont.pingfangFont(ofSize: PTW(16), weight: .medium),
                          NSAttributedString.Key.foregroundColor:UIColor.colorWithHex("#7863A6", 0.5)]
        txt.attributedPlaceholder = NSAttributedString.init(string: "E-mail", attributes: attributes)
        txt.modifyClearButton(KImaged("coco_editTxt_close"))
        txt.textColor = UIColor.colorWithHex("#7863A6", 1)
        txt.font = UIFont.pingfangFont(ofSize:PTW(16), weight: .medium)
        return txt
    }()

    lazy var verifyContainer: UIView = {
        let contain = UIView()
        contain.backgroundColor = UIColor.colorWithHex("#F5F5F5")
        contain.layer.cornerRadius = PTW(65/2)
        contain.layer.masksToBounds = true
        return contain
    }()
    
    lazy var verifyImg: UIImageView = {
        let em = UIImageView()
        em.image = KImaged("coco_mine_vercode")
        return em
    }()
    
    lazy var verifyTxtField: UITextField = {
        let txt = UITextField()
        txt.backgroundColor = .clear
        txt.clearButtonMode = .whileEditing
        let attributes = [NSAttributedString.Key.font:UIFont.pingfangFont(ofSize: PTW(16), weight: .medium),
                          NSAttributedString.Key.foregroundColor:UIColor.colorWithHex("#7863A6", 0.5)]
        txt.attributedPlaceholder = NSAttributedString.init(string: "Verification code", attributes: attributes)
        txt.modifyClearButton(KImaged("coco_editTxt_close"))
        txt.textColor = UIColor.colorWithHex("#7863A6", 1)
        txt.font = UIFont.pingfangFont(ofSize: PTW(16), weight: .medium)
        txt.delegate = self
        return txt
    }()
    
    lazy var lineLbl: UILabel = {
        let line = UILabel()
        line.backgroundColor = UIColor.colorWithHex("#FFFFFF", 0.3)
        return line
    }()
    
    lazy var bindEmailBtn: UIButton = {
        let code = UIButton(type: .custom)
        code.setTitle("Bind Email", for: .normal)
        code.setTitleColor(UIColor.colorWithHex("#FFFFFF"), for: .normal)
        code.titleLabel?.font = UIFont.pingfangFont(ofSize: PTW(17), weight: .medium)
        code.addTarget(self, action: #selector(bindAction), for: .touchUpInside)
        code.layer.cornerRadius = PTW(65/2)
        code.layer.masksToBounds = true
        code.backgroundColor = UIColor.gradientFromColor(colors: [UIColor.colorWithHex("#7038FF").cgColor,UIColor.colorWithHex( "#FF3DE1").cgColor], direction: .Horizontal, range: PTW(225))
        return code
    }()
    
    lazy var codeBtn: COTimerBtn = {
        let code = COTimerBtn()
        code.setTitleColor(UIColor.colorWithHex("#FF4D95"), for: .normal)
        code.setup("Send Code", timeTitlePrefix: "", aTimeLength: 60)
        code.clickBtnEvent = {() -> Void in
            if !code.isWorking{
                //访问接口，获取验证码
                code.isWorking = true
                self.sendCodeAction()
            }
        }
        return code
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.addnav()
        self.title = "Bind Email"
        self.view.addSubview(self.containView)
        self.containView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.navView.snp.bottom)
        }
        
        self.containView.addSubview(self.emailContainer)
        self.emailContainer.addSubview(self.emailImg)
        self.emailContainer.addSubview(self.emailTxtField)
        self.emailContainer.addSubview(self.lineLbl)
        self.emailContainer.addSubview(self.codeBtn)
        self.containView.addSubview(self.verifyContainer)
        self.verifyContainer.addSubview(self.verifyImg)
        self.verifyContainer.addSubview(self.verifyTxtField)
        self.containView.addSubview(self.bindEmailBtn)
        
        self.emailContainer.snp.makeConstraints { make in
            make.width.equalTo(SCREENWIDTH - PTW(40))
            make.height.equalTo(PTW(65))
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(PTW(40))
        }
        self.emailImg.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(20), PTW(20)))
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(PTW(20))
        }
        self.emailTxtField.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(self.emailImg.snp.right).offset(PTW(10))
            make.right.equalToSuperview().offset(-PTW(110))
        }
        self.lineLbl.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(2), PTW(25)))
            make.centerY.equalToSuperview()
            make.left.equalTo(self.emailTxtField.snp.right).offset(PTW(5))
        }
        self.codeBtn.snp.makeConstraints { make in
            make.left.equalTo(self.lineLbl.snp.right)
            make.right.bottom.equalTo(self.emailContainer)
            make.height.equalTo(PTW(50))
        }
        self.verifyContainer.snp.makeConstraints { make in
            make.width.equalTo(SCREENWIDTH - PTW(40))
            make.height.equalTo(PTW(65))
            make.centerX.equalToSuperview()
            make.top.equalTo(self.emailContainer.snp.bottom).offset(PTW(25))
        }
        self.verifyImg.snp.makeConstraints { make in
            make.size.equalTo(PTW(20))
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(PTW(20))
        }
        self.verifyTxtField.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(self.verifyImg.snp.right).offset(PTW(10))
            make.right.equalToSuperview().offset(-PTW(10))
        }
        self.bindEmailBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(PTW(225), PTW(65)))
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-PTW(150))
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.containView.clipsCorners(corners: [.topLeft,.topRight], radius: PTW(30))
    }
    
    func sendCodeAction(){
        if (emailTxtField.text?.isEmptyStr == true){
            UIToolHelper.makeToast("Please enter email！")
            codeBtn.restore()
            return
        }
        // 验证字符串是否为Email
        if (emailTxtField.text?.isEmail() == false){
            UIToolHelper.makeToast("Please enter a valid email")
            codeBtn.restore()
            return
        }
        var params = [String:Any]()
        params["email"] = emailTxtField.text
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.emailCode(param: params), modelType: CONSObjectModel.self) {[weak self] code, object, success in
            UIToolHelper.hideHUD()
            DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute:{
                UIToolHelper.makeToast("Successful!")
                self?.codeBtn.restore()
            })
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
            UIToolHelper.makeToast("Network error,Please try again later")
        }
    }
    
    @objc func bindAction(){
        if(self.emailTxtField.text?.isEmptyStr == true || self.emailTxtField.text?.isEmail() == false){
            UIToolHelper.makeToast("Please enter a valid email.")
            return
        }
        if (self.verifyTxtField.text?.isEmptyStr == true){
            UIToolHelper.makeToast("Your information is incomplete.")
            return
        }
        var params = [String:Any]()
        params["email"] = emailTxtField.text
        params["phone"] = verifyTxtField.text
        UIToolHelper.showHUD()
        var target = COBaseApi.userGuestEmail(param: params)
        if type == 1{
            target = COBaseApi.bindEmailGetCoins(param: params)
        }
        COHttpManager.request(target: target, modelType: CONSObjectModel.self) {[weak self] code, object, success in
            UIToolHelper.hideHUD()
            if (self?.type == 1){
                UIToolHelper.makeToast("Bind success,20 coins free for you!")
            }else{
                UIToolHelper.makeToast("Success!")
            }
            var curmodel = COUserInfoManager.shared.curUser
            curmodel?.userResponse.email = (self?.emailTxtField.text)!
            COUserInfoManager.shared.curUser = curmodel
            COUserInfoManager.coSaveInfo()
            DispatchQueue.main.asyncAfter(deadline: .now()+1, execute: {
                self?.navigationController?.popViewController(animated: true)
            })
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
            UIToolHelper.makeToast("email or verification code is incorrect!")
        }
    }
}

extension COBindEmailController:UITextFieldDelegate{
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text!
        let len = text.count + string.count - range.length
        return len<=12
    }
}
